
package com.ruoyi.common.utils.wrapper;

import com.ruoyi.common.utils.sm2.KeyConstant;
import com.ruoyi.common.utils.sm2.SM2Util;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 请求加解密过滤器
 *
 * @author 猴哥
 */
//@Component
public class RequestHandler implements Filter {
    /**
     * 进行请求加密
     */
    @SneakyThrows
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // form-data不校验
        if ("application/x-www-form-urlencoded".equals(request.getContentType())) {
            chain.doFilter(request, response);
            return;
        }

        // 拿到加密串
        String data = new RequestWrapper((HttpServletRequest) request).getBody();
        if (StringUtils.isEmpty(data)) {
            chain.doFilter(request, response);
            return;
        }
        // 解析
        String body = SM2Util.decrypt(KeyConstant.PRIVATE_KEY, data);
        request = new BodyRequestWrapper((HttpServletRequest) request, body);
        chain.doFilter(request, response);
    }
}